package com.example.myapplication.TouchDemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;

import com.example.myapplication.R;

public class TouchDemoActivity extends AppCompatActivity {
    VelocityTracker velocityTracker;
    TestView testView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_touch_demo);
        testView = findViewById(R.id.touchTestView);
        testView.setOnTouchListener(new mOnTouch());
    }

    public class mOnTouch implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int x1,y1;
            x1 = (int) event.getX();
            y1 = (int) event.getY();

            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    testView.setXY(x1,y1);
                    testView.invalidate();
                    if(velocityTracker==null){
                        velocityTracker = VelocityTracker.obtain();
                    }else{
                        velocityTracker.clear();;
                    }
                    velocityTracker.addMovement(event);
                    break;

                case MotionEvent.ACTION_MOVE:
                    testView.setXY(x1,y1);
                    testView.invalidate();
                    velocityTracker.addMovement(event);
                    velocityTracker.computeCurrentVelocity(1000);
                    Log.e("Velocity", "x速度: "+velocityTracker.getXVelocity()+"像素/每秒"+"y速度: "+velocityTracker.getYVelocity()+"像素/每秒");
                    break;

                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    if(velocityTracker!=null){
                        velocityTracker.recycle();
                        velocityTracker = null;
                    }
                    break;

            }
            return true;
        }
    }
}